<template>
	<div class="login">
		<el-form ref="myForm" :model="form" label-width="80px" :rules="rules">
			<el-form-item label="用户名" prop="name">
				<el-input v-model="form.name"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input v-model="form.password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitLogin('myForm')"
					>登录</el-button
				>
				<el-button @click="reset('myForm')">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { userLogin, getUserInfo } from '@/api/user';
export default {
	data() {
		return {
			form: {
				name: '',
				password: '',
			},
			rules: {
				name: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'blur',
					},
				],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
				],
			},
		};
	},
	methods: {
		submitLogin(e) {
			// 数据校验
			this.$refs[e].validate((valid) => {
				if (valid) {
					// 登录
					userLogin(this.form).then((res) => {
						console.log(res);
						if (res.code == 0) {
							// 登陆成功
							window.localStorage.setItem(
								'token',
								res.data.token
							);
							getUserInfo().then((res) => {
								console.log(res);
								this.$store.commit('changeUserInfo', res.data);
							});
							this.$router.push({ path: '/' });
							return this.$message.success(res.mes);
						} else {
							return this.$message.info(res.mes);
						}
					});
				} else {
					return this.$message.info('校验未通过');
				}
			});
		},
		// 重置
		reset(e) {
			this.$refs[e].resetFields();
		},
	},
};
</script>

<style>
</style>